<?

class WebUser extends CWebUser {
    
    const ROLE_ROOT = 'root';
    const ROLE_ADMIN = 'admin';
    const ROLE_DEV = 'developer';
    const ROLE_MANAG = 'manager';
    const ROLE_CLIENT = 'client';
    const ROLE_USER = 'user';
    const ROLE_GUEST = 'guest';
    
    private $_model = null;
    
    function getRole() {
        $m = $this->getModel();
        if($m->id > 0){
            $role = $m->role;
            $role = empty($role) ? self::ROLE_USER : $role;
        }else{
            $role = Yii::app()->user->isGuest ? self::ROLE_GUEST : self::ROLE_USER;
        }
        return $role;
    }
    
    function getModel(){
        if (!$this->isGuest && is_null($this->_model)){
            $this->_model = Users::model()->findByPk($this->id);
        }
        return $this->_model;
    }
    
    function isRoot(){ return Yii::app()->user->checkAccess(self::ROLE_ROOT); }
    function isAdmin(){ return Yii::app()->user->checkAccess(self::ROLE_ADMIN); }
    function isDeveloper(){ return Yii::app()->user->checkAccess(self::ROLE_DEV); }
    function isManager(){ return Yii::app()->user->checkAccess(self::ROLE_MANAG); }
    function isClient(){ return Yii::app()->user->checkAccess(self::ROLE_CLIENT); }
    function isUser(){ return Yii::app()->user->checkAccess(self::ROLE_USER); }
    
    function isAuth(){ return Yii::app()->user->isUser(); }
    
    function message($object, $type, $message){ $this->setFlash(get_class($object).'.'.rand().'.'.$type, $message); }
    function successMessage($object, $message){ $this->message($object, 'success', $message); }
    function noticeMessage($object, $message){ $this->message($object, 'notice', $message); }
    function errorMessage($object, $message){ $this->message($object, 'error', $message); }
    
    function getBackUrl($getRequestVal='backurl', $defaultUrl='/'){
        $url = $defaultUrl;
        $ref = $_SERVER['HTTP_REFERER'];
        if(isset($_GET[$getRequestVal])){
            $url = urldescode($_GET[$getRequestVal]);
        }elseif(!empty($ref)){
            $ref = parse_url($ref);
            if(isset($ref['query']) and !empty($ref['query'])){
                parse_str($ref['query'], $q);
                
                if(isset($q[$getRequestVal])){
                    $url = urldecode($q[$getRequestVal]);
                }else{
                    $url = $ref['path'];
                    if(isset($ref['query'])) $url .= '?'.$ref['query'];
                    if(isset($ref['fragment'])) $url .= '#'.$ref['fragment'];
                }
            }
        }
        return $url;
    }
    
}
